<template>
	<view class="education-page">
		<nav-header title="添加教育经历"></nav-header>

		<view class="content" :style="{ marginTop: statusBarHeight + 44 + 'px' }">
			<view class="page-title">添加教育经历</view>
			<view class="subtitle">从最高学历写起</view>

			<view class="form-container">
				<!-- School Name -->
				<view class="form-item">
					<text class="label required">学校名称</text>
					<input class="input" type="text" placeholder="例如：北京大学" v-model="formData.school" />
				</view>
				
				<view class="form-item">
					<text class="label required">专业</text>
					<input class="input" type="text" placeholder="例如：软件工程" v-model="formData.major" />
				</view>
				
				<!-- Degree -->
				<view class="form-item">
					<text class="label required">学历</text>
					<view class="input picker" @click="showDegreePicker = true">
						<text v-if="formData.degree">{{ formData.degree }}</text>
						<text v-else class="placeholder">请选择学历</text>
						<text class="arrow">›</text>
					</view>
				</view>
				
				<!-- Time Period -->
				<view class="form-item">
					<text class="label required">时间段</text>
					<view class="time-range">
						<!-- Start Time -->
						<picker mode="date" :value="formData.startDate" fields="month" @change="handleStartTimeChange">
							<view class="time-picker">
								<text>{{ formData.startDate ? formData.startDate : '开始时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
				
						<text class="time-separator">至</text>
				
						<!-- End Time -->
						<picker mode="date" :value="formData.endDate" fields="month" @change="handleEndTimeChange">
							<view class="time-picker">
								<text>{{ formData.endDate ? formData.endDate : '结束时间' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>
				
				<!-- Description -->
				<view class="form-item">
					<view class="" style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
						<text class="label">学习情况</text>
						<button class="generate-btn" @click="generateEducation">
							<text class="generate-icon">✨</text>
							AI生成
						</button>
					</view>
					<textarea class="textarea" placeholder="请填写学习情况" v-model="formData.description"
						maxlength="500"></textarea>
					<text class="word-count">{{ formData.description.length }}/500</text>
				</view>
				
				
				<!-- 底部按钮 -->
				<view class="bottom">
					<!-- Delete Button -->
					<view class="delete-action" v-if="!isAdding">
						<button class="delete-btn" @click="confirmDelete">删除</button>
					</view>
					<!-- Save Button -->
					<view class="action-bar">
						<button class="save-btn" @click="saveEducation">保存</button>
					</view>
				</view>
			</view>
		</view>


		<!-- Degree Picker -->
		<uni-popup ref="degreePopup" type="bottom" @change="handleDegreePopupChange">
			<view class="picker-popup">
				<view class="picker-header">
					<text class="cancel-btn" @click="showDegreePicker = false">取消</text>
					<text class="title">选择学历</text>
					<text class="confirm-btn" @click="confirmDegree">确定</text>
				</view>
				<picker-view class="picker-view" :value="degreeIndex" @change="handleDegreeChange">
					<picker-view-column>
						<view class="picker-item" v-for="item in degrees" :key="item">{{ item }}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</uni-popup>

		<!-- Delete Confirmation -->
		<uni-popup ref="deleteConfirmPopup" type="dialog">
			<uni-popup-dialog title="删除确认" content="确定要删除这条教育经历吗？删除后将无法恢复。" :beforeClose="true"
				@confirm="deleteEducation" @close="closeDeleteConfirm"></uni-popup-dialog>
		</uni-popup>
		
		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popupEdu" background-color="#fff" mask-background-color="rgba(0,0,0,0)"
				:is-mask-click="false" type="bottom" borderRadius='20px 20px 0 0 '>
				<view class="popup-content">
					<view class="popup-header">
						<text class="popup-title">AI生成</text>
						<uni-icons type="closeempty" size="24" @click="closePopupEdu"></uni-icons>
					</view>
					<view class="popup-body">
						<text>{{AIContent}}</text>
					</view>
					<view class="popup-footer">
						<button class="popup-btn" @click="rewriteEdu">重写</button>
						<button type="primary" class="popup-btn" @click="replaceEdu">替换</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		watch,
		nextTick
	} from 'vue'
	import NavHeader from '@/components/nav-header.vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		getEducationExperienceList,
		getEducationExperienceDetail,
		addEducationExperience,
		updateEducationExperience,
		deleteEducationExperience,
		generateEducationDescription
	} from '@/api/edit/education'
	import env from '@/env'
	import { useAuthStore } from '@/store/index';
	import { useResumeStore } from '@/store/resume.js'
	import { mockInterviewWebSocketProcess } from '@/api/ai'
	import { useWebSocket } from '@/utils/useWebSocket'
	
	const authStore = useAuthStore();
	const { messages, isConnected, connect, sendMessage, close, onMessage } = useWebSocket(env.websocket)
	const popupEdu = ref(null)
	const AIContent = ref(null)
	const statusBarHeight = ref(20)
	const degreePopup = ref(null)
	const deleteConfirmPopup = ref(null)

	const isAdding = ref(true)
	const currentId = ref(null)
	const showDegreePicker = ref(false)
	const degreeIndex = ref([0])
	const degrees = [
		'博士', '硕士', '本科', '大专', '高中', '中专', '初中及以下'
	]
	const currentYear = new Date().getFullYear()
	const formData = reactive({
		school: '',
		major: '',
		degree: '',
		startDate: '',
		endDate: '',
		description: ''
	})
	const currentIndex = ref(-1)
	const resumeStore = useResumeStore()
	const isGenerating = ref(false)

	// 注册WebSocket消息处理函数
	onMessage((data) => {
		uni.hideLoading();
		try {
			if (typeof data === 'string') {
				try {
					const parsedData = JSON.parse(data);
					if (parsedData.topic === 'EDUCATION_EXPERIENCE') {
						if (parsedData.content === '[DONE]' || parsedData.content.includes('[DONE]')) {
							isGenerating.value = false;
							uni.hideLoading();
							uni.showToast({
								title: '生成完成',
								icon: 'success'
							});
							return;
						}
						AIContent.value += parsedData.content;
						return;
					}
				} catch (e) {
					// 如果不是JSON格式，直接处理字符串
					if (data === '[DONE]' || data.includes('[DONE]')) {
						isGenerating.value = false;
						uni.hideLoading();
						uni.showToast({
							title: '生成完成',
							icon: 'success'
						});
						return;
					}
					AIContent.value += data;
				}
			}
		} catch (error) {
			console.error('处理WebSocket消息出错:', error);
		}
	});

	onLoad(async (options) => {
		if (options.index) {
			currentId.value = options.index
			isAdding.value = false
			await fetchEducationDetail(options.index)
		} else {
			isAdding.value = true
			resetForm()
		}
	})

	onUnload(() => {
		// 关闭WebSocket连接
		close();
		if (isGenerating.value) {
			isGenerating.value = false;
		}
	});

	onMounted(() => {
		const systemInfo = uni.getSystemInfoSync()
		statusBarHeight.value = systemInfo.statusBarHeight

		// 启动时先尝试连接WebSocket
		try {
			connect().then(() => {
				console.log('WebSocket连接成功，可以接收消息');
			}).catch(err => {
				console.error('WebSocket连接失败:', err);
			});
		} catch (e) {
			console.error('连接WebSocket异常:', e);
		}
	})

	function resetForm() {
		formData.school = ''
		formData.major = ''
		formData.degree = ''
		formData.startDate = ''
		formData.endDate = ''
		formData.description = ''
	}

	async function fetchEducationDetail(id) {
		try {
			uni.showLoading({
				title: '加载中...'
			})
			const res = await getEducationExperienceDetail(id)
			if (res.code === 200 && res.data) {
				// Object.assign(formData, res.data)
				const data = res.data
				formData.school = data.schoolName
				formData.major = data.major
				formData.degree = data.educationalBackground
				formData.startDate = data.startDate
				formData.endDate = data.endDate
				formData.description = data.academicPerformance
				
				if (formData.degree) {
					const degreeIdx = degrees.findIndex(d => d === formData.degree)
					if (degreeIdx !== -1) degreeIndex.value = [degreeIdx]
				}
				if (formData.startDate) {
					const parts = formData.startDate.split('.')
					if (parts.length === 2) {
						const yearIdx = years.findIndex(y => y === parseInt(parts[0]))
						const monthIdx = months.findIndex(m => m === parseInt(parts[1]))
						if (yearIdx !== -1 && monthIdx !== -1) startDateIndex.value = [yearIdx, monthIdx]
					}
				}
				if (formData.endDate && formData.endDate !== '至今') {
					const parts = formData.endDate.split('.')
					if (parts.length === 2) {
						const yearIdx = years.findIndex(y => y === parseInt(parts[0]))
						const monthIdx = months.findIndex(m => m === parseInt(parts[1]))
						if (yearIdx !== -1 && monthIdx !== -1) endDateIndex.value = [yearIdx, monthIdx]
					}
				}
			}
		} catch (e) {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	const deleteEducation = async () => {
		if (!currentId.value) return
		try {
			uni.showLoading({
				title: '删除中...'
			})
			const res = await deleteEducationExperience(currentId.value)
			if (res.code === 200) {
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '删除失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '删除失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	
	const handleDegreePopupChange = (e) => {
		if (!e.show) showDegreePicker.value = false
	}
	const handleDegreeChange = (e) => {
		degreeIndex.value = e.detail.value
	}
	const confirmDegree = () => {
		formData.degree = degrees[degreeIndex.value[0]]
		showDegreePicker.value = false
	}
	const handleStartTimeChange = (e) => {
		formData.startDate = e.detail.value
	}
	
	const handleEndTimeChange = (e) => {
		formData.endDate = e.detail.value
	}

	const saveEducation = async () => {
		if (!formData.school) {
			uni.showToast({
				title: '请输入学校名称',
				icon: 'none'
			});
			return
		}
		if (!formData.degree) {
			uni.showToast({
				title: '请选择学历',
				icon: 'none'
			});
			return
		}
		if (!formData.startDate) {
			uni.showToast({
				title: '请选择开始时间',
				icon: 'none'
			});
			return
		}
		if (formData.startDate && formData.endDate) {
			const startParts = formData.startDate.split('.')
			const endParts = formData.endDate.split('.')
			const startYear = parseInt(startParts[0])
			const startMonth = parseInt(startParts[1])
			const endYear = parseInt(endParts[0])
			const endMonth = parseInt(endParts[1])
			if (endYear < startYear || (endYear === startYear && endMonth < startMonth)) {
				uni.showToast({
					title: '结束时间不能早于开始时间',
					icon: 'none'
				});
				return
			}
		}
		try {
			uni.showLoading({
				title: '保存中...'
			})
			let res
			const params = {
				// TODO:修改
				// resumeId: '1916784587136589826',
				resumeId:resumeStore.resumeId,
				schoolName: formData.school,
				educationalBackground: formData.degree,
				major: formData.major,
				startDate: formData.startDate,
				endDate: formData.endDate == '' ? '' : formData.endDate,
				academicPerformance: formData.description
			}
			if (isAdding.value) {
				res = await addEducationExperience(params)
			} else {
				params.id = currentId.value
				res = await updateEducationExperience(params)
			}
			if (res.code === 200) {
				uni.showToast({
					title: isAdding.value ? '添加成功' : '更新成功',
					icon: 'success'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: res.msg || '保存失败',
					icon: 'none'
				})
			}
		} catch (e) {
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}
	watch(showDegreePicker, (val) => {
		if (val) degreePopup.value.open()
		else degreePopup.value.close()
	})
	const closeDeleteConfirm = () => {
		deleteConfirmPopup.value.close()
	}
	const confirmDelete = () => {
		deleteConfirmPopup.value.open()
	}
	
	const generateEducation = async() => {
		try {
			// 避免重复请求
			if (isGenerating.value) {
				return;
			}
			
			isGenerating.value = true;
			AIContent.value = ''; // 清空之前的内容
			popupEdu.value.open();
			
			uni.showLoading({
				title: 'AI生成中...'
			});
			
			// 创建请求数据
			const requestData = {
				type: 'EDUCATION_EXPERIENCE',
				aiResumeEducationExperienceBo: {
					resumeId: resumeStore.resumeId,
					schoolName: formData.school,
					educationalBackground: formData.degree,
					major: formData.major
				}
			};
			
			// 检查WebSocket连接状态
			if (!isConnected.value) {
				console.log('WebSocket未连接，尝试连接...');
				await connect();
				console.log('WebSocket连接已建立');
			} else {
				console.log('WebSocket已连接，状态正常');
			}
			
			// 确保WebSocket已连接后，调用HTTP接口触发后端推送消息
			console.log('准备调用HTTP接口触发后端推送...');
			
			// 调用HTTP接口触发后端推送WebSocket消息
			mockInterviewWebSocketProcess(requestData).then(res => {
				// 如果很长时间没收到WebSocket消息，可能后端未正确推送，此时使用HTTP响应结果
				setTimeout(() => {
					if (isGenerating.value && !AIContent.value) {
						console.log('未收到WebSocket消息，尝试使用HTTP响应');
						try {
							isGenerating.value = false;
							// 尝试回退到常规HTTP请求方式
						} catch (err) {
							console.error('处理HTTP响应失败:', err);
						}
					}
				}, 5000); // 5秒后检查
				
			}).catch(err => {
				console.error('调用HTTP接口失败:', err);
				// 失败时回退到常规HTTP请求方式
			});
			
		} catch (error) {
			console.error('生成教育经历失败', error);
			uni.hideLoading();
			isGenerating.value = false;
			uni.showToast({
				title: '生成失败',
				icon: 'none'
			});
		}
	}
	
	// 关闭AI生成弹窗
	const closePopupEdu = () => {
		uni.hideLoading()
		popupEdu.value.close()
	}
	
	// 重写AI生成内容
	const rewriteEdu = () => {
		// 确保上一次生成已经结束
		isGenerating.value = false;
		setTimeout(() => {
			generateEducation();
		}, 300);
	}
	
	// 替换AI生成内容
	const replaceEdu = () => {
		popupEdu.value.close()
		formData.description = AIContent.value
	}
</script>

<style lang="scss" scoped>
	.education-page {
		min-height: 100vh;
		background-color: #ffffff;
		padding-bottom: 70px;
		flex-direction: column;

		.content {
			flex: 1;
			padding: 20px;
			padding-bottom: 100px;

			.page-title {
				font-size: 24px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}

			.subtitle {
				font-size: 14px;
				color: #999;
				margin-bottom: 24px;
			}
			.form-container {
				background-color: #fff;
				border-radius: 12px 12px 0 0;
				padding-bottom: 20px;
				.form-item {
					margin-bottom: 24px;
					position: relative;
				
					.label {
						font-size: 16px;
						color: #333;
						margin-bottom: 10px;
						display: block;
						font-weight: 500;
						
						&.required:after {
							content: '*';
							color: #ff4d4f;
							margin-left: 4px;
						}
					}
				
					.input {
						height: 44px;
						line-height: 44px;
						border-bottom: 1px solid #e5e5e5;
						font-size: 16px;
						color: #333;
						width: 100%;
				
						&.picker {
							display: flex;
							align-items: center;
							justify-content: space-between;
				
							.placeholder {
								color: #999;
							}
				
							.arrow {
								font-size: 20px;
								color: #ccc;
								transform: rotate(90deg);
							}
						}
				
						&.disabled {
							color: #666;
						}
					}
				
					.time-range {
						display: flex;
						align-items: center;
						justify-content: space-around;
				
						.time-picker {
							flex: 1;
							height: 44px;
							line-height: 44px;
							border-bottom: 1px solid #e5e5e5;
							font-size: 16px;
							color: #333;
				
							&.disabled {
								color: #666;
							}
				
							.placeholder {
								color: #999;
							}
						}
				
						.time-separator {
							margin: 0 15px;
							color: #666;
						}
					}
				
					.current-switch {
						display: flex;
						align-items: center;
						justify-content: flex-end;
						margin-top: 10px;
				
						text {
							font-size: 14px;
							color: #666;
							margin-right: 8px;
						}
					}
				
					.textarea {
						border: 1px solid #e5e5e5;
						border-radius: 4px;
						padding: 12px;
						font-size: 15px;
						color: #333;
						width: 100%;
						box-sizing: border-box;
					}
				
					.word-count {
						font-size: 12px;
						color: #999;
						position: absolute;
						right: 10px;
						bottom: 10px;
					}
				}
			
				.bottom {
					position: fixed;
					bottom: 0;
					left: 0;
					right: 0;
					height: 70px;
					background-color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 0 20px;
					box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
					z-index: 9;
					gap: 30rpx;
				}

				.delete-action {

					.delete-btn {
						width: 100%;
						height: 44px;
						line-height: 44px;
						text-align: center;
						border-radius: 22px;
						font-size: 16px;
						color: #ff4d4f;
						background-color: #fff;
						border: 1px solid #ff4d4f;
					}
				}
				
				.action-bar {
					flex: 1;
				
					.save-btn {
						width: 100%;
						height: 44px;
						line-height: 44px;
						background-color: #5ac725;
						color: #FFFFFF;
						font-size: 16px;
						font-weight: 500;
						border-radius: 22px;
					}
				}
			}
		}

		.picker-popup {
			background-color: #fff;
			border-radius: 12px 12px 0 0;
			overflow: hidden;

			.picker-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 12px 16px;
				border-bottom: 1px solid #f0f0f0;

				.title {
					font-size: 16px;
					color: #333;
				}

				.cancel-btn {
					font-size: 15px;
					color: #999;
				}

				.confirm-btn {
					font-size: 15px;
					color: #5ac725;
				}
			}

			.picker-view {
				width: 100%;
				height: 240px;

				.picker-item {
					line-height: 36px;
					text-align: center;
					font-size: 16px;
				}
			}
		}
	}
</style>